package com.lcxw.hxzbapi.controller.friendcirclecontroller;

import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbcommon.common.ObsUtil;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@RestController
@RequestMapping("api/resource")
@Slf4j
public class ResourceUploadController {

    private ObsUtil obsUtil = new ObsUtil();

    @PostMapping("/upload")
    public Response uploadResource(HttpServletRequest request) {

        String userId = request.getParameter("userId");
        String type = request.getParameter("type");

        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
            .getFiles("MultipartFile");

        log.info("{} 上传 朋友圈动态文件，文件类型为 {}", userId, type);

        if (type.equals("picture") && files.size() > 9) {
            return Response.error(3001, "上传图片不能超过9个");
        } else if (type.equals("video") && files.size() > 1) {
            return Response.error(3001, "上传视频不能超过1个");
        }
        List<String> urls = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                String fileName = "friendCircle/" + userId + "/" + file.getOriginalFilename();
                String url = obsUtil.uploadResrouce(fileName, file.getBytes());
                urls.add(url);
            }
        } catch (Exception e) {
            log.error("上传文件到obs失败");
            return Response.error(6001, "上传文件到obs失败");
        }
        return Response.ok(urls);
    }
}
